<template>
	<swiper class="home-swiper" :current="activeIndex" @change="change">
		<swiper-item v-for="(item,index) in tab" :key="index" class="swiper-item">
			<list-item :list="listCatchData[index]" :load="load[index]" @loadMore="loadMore"></list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue';
	export default {
		name: "list",
		components: {
			listItem,
		},
		props: {
			tab: {
				type: Array,
				default () {
					return []
				}
			},
			activeIndex: {
				type: Number,
				default: 0
			},
		},
		data() {
			return {
				list: [],
				listCatchData: {},
				load:{},
				pageSize:4,
			};
		},
		watch: {
			tab(newValue) {
				if (newValue === 0) return
				this.listCatchData = {}
				this.load = {}
				this.getList(this.activeIndex)
			}
		},
		created() {
			// this.getList(0)
			uni.$on('update_article',(res) => {
				if (res === 'follow') {
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				}
			})
		},
		methods: {
			change(e) {
				const {
					current
				} = e.detail
				if (!this.listCatchData[current] || this.listCatchData[current].length === 0) {
					// 当数据不存在或者长度是0的情况下,才去请求数据
					this.getList(current)
				}
				this.$emit('change', current)
			},
			getList(current) {
				if (!this.load[current]) {
					this.load[current] = {
						page: 1,
						loading:'loading'
					}
				}
				this.$Api.get_list({
					name: this.tab[current].name,
					page: this.load[current].page,
					pageSize: this.pageSize
				}).then((res) => {
					// console.log(res);
					const {
						data
					} = res;
					if (data.length===0) {
						let oldLoad = {}
						oldLoad.loading = 'noMore'
						oldLoad.page = this.load[current].page
						this.$set(this.load,current,oldLoad)
						this.$forceUpdate();
						return
					}
					// this.list = data;
					// this.listCatchData[current] = data;
					let oldList = this.listCatchData[current] || []
					oldList.push(...data)
					this.$set(this.listCatchData, current, oldList)
				})
			},
			loadMore(){
				if (this.load[this.activeIndex].loading == 'noMore') return
				this.load[this.activeIndex].page++
				console.log('what');
				this.getList(this.activeIndex)
			}
		}
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;
		overflow: hidden;

		.swiper-item {
			height: 100%;

			.list-scroll {
				height: 100%;
			}
		}
	}
</style>
